/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.common.nonlitigation.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HttpUtils;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.DocumentSentAddressInfoRequest;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.CaseDocumentSendinfoConfirmVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.dto.*;
import com.icinfo.cloud.provider.punish.common.nonlitigation.enums.*;
import com.icinfo.cloud.provider.punish.common.nonlitigation.mapper.CaseNonLitigationExecuteRecordMapper;
import com.icinfo.cloud.provider.punish.common.nonlitigation.model.CaseNonLitigationExecuteRecord;
import com.icinfo.cloud.provider.punish.common.nonlitigation.service.ICaseNonLitigationExecuteRecordService;
import com.icinfo.cloud.provider.punish.common.nonlitigation.utils.NonLitigationUtil;
import com.icinfo.cloud.provider.punish.common.nonlitigation.vo.CaseNonLitigationExecuteDetailVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.vo.CaseNonLitigationExecuteRecordDetailVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.vo.CaseNonLitigationExecuteRecordVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.vo.NonLitigationPartiesMaterialInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseAttachmentInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandlePersonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesLegalInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesLegalInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.ICaseDocumentSendinfoConfirmService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.mapper.util.StringUtil;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 描述: 非诉执行记录表 case_non_litigation_execute_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年04月07日
 */
@Service
public class CaseNonLitigationExecuteRecordServiceImpl extends MyBatisServiceSupport implements ICaseNonLitigationExecuteRecordService {
    @Value("${nonLitigation.url-irs}")
    private String url;
    @Value("${nonLitigation.api.getToken-irs}")
    private String getToken;
    //uploadFile未提供IRS接口，调用会报错
    @Value("${nonLitigation.api.uploadFile}")
    private String uploadFile;
    @Value("${nonLitigation.api.uploadFileList-irs}")
    private String uploadFileList;
    @Value("${nonLitigation.api.nonLitigationRegister-irs}")
    private String nonLitigationRegister;
//    @Value("${nonLitigation.username}")
//    private String username;
//    @Value("${nonLitigation.password}")
//    private String password;
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseNonLitigationExecuteRecordServiceImpl.class);

    private static final String ACCESS_XTBH = "53";
    private static final String COURT_CODE = "1396";
    private static final String XZXWZL_CODE = "17";
    @Resource
    private CaseNonLitigationExecuteRecordMapper caseNonLitigationExecuteRecordMapper;

    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseDocumentSendinfoConfirmService caseDocumentSendinfoConfirmService;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    /**
     * 描述：行政非诉智审网上立案
     *
     * @param requestDto 请求dto
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/10
     */
    @Override
    public Map<String, Object> nonLitigationExecuteRegister(CaseNonLitigationExecuteRequestDto requestDto) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", Constant.STRING_FAIL_EN);
        UserDTO userDTO = UserUtil.getUserInfo();
        String errorMsg = "";
        String caseId = requestDto.getCaseId();
        CaseNonLitigationExecuteRecord executeRecord = new CaseNonLitigationExecuteRecord();
        Map<String, Object> paramMap = new HashMap<>();
        try {
            String token = getBearerToken(requestDto.getIpAddress());
            if (ObjectUtil.isEmpty(token)) {
                throw new BusinessException("获取token失败");
            }
            //组装基本信息
            assembleParamInfo(paramMap, requestDto.getCaseId(), userDTO);
            //上传并获取申请材料信息
            List<Map<String, Object>> mapList = assembleApplicationMaterial(requestDto, token);
            paramMap.put("sqclxx", mapList);
            String result = NonLitigationUtil.doIRSHttpPostWithToken(url + nonLitigationRegister, "Bearer " + token, paramMap);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (ObjectUtil.isNotEmpty(jsonObject.get("code"))) {
                    if (Constant.STRING_200.equals(jsonObject.getString("code"))) {
                        executeRecord.setExecuteStatus(Constant.STRING_1);
                        executeRecord.setExecuteResult(Constant.STRING_1);
                        resultMap.put("code", Constant.STRING_SUCCESS_EN);
                        String lasqid = jsonObject.get("data") + "";
                        executeRecord.setNonLitigationCaseId(lasqid);
                        logger.info("Non-litigation Execute Register Successfully,caseId:{},result:{}", caseId , jsonObject.toString());
                    } else {
                        executeRecord.setExecuteResult(Constant.STRING_0);
                        executeRecord.setExecuteFailReason(jsonObject.getString("msg"));
                        errorMsg = "非诉执行失败：" + jsonObject.getString("msg");
                        logger.info("Non-litigation Execute Register Fail,caseId:{},result:{}", caseId,jsonObject.toString());
                    }
                } else {
                    executeRecord.setExecuteResult(Constant.STRING_0);
                    executeRecord.setExecuteFailReason(jsonObject.getString("message"));
                    errorMsg = "非诉执行失败：" + jsonObject.getString("message");
                    logger.info("Non-litigation Execute Register Fail,caseId:{},result:{}", caseId,jsonObject.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            errorMsg = "非诉执行失败：" + e.getMessage();
        }
        CaseNonLitigationExecuteRecord record = getCaseNonLitigationExecuteRecordByCaseId(requestDto.getCaseId());

        executeRecord.setCaseId(requestDto.getCaseId());
        executeRecord.setExecuteCourtCode(COURT_CODE);
        executeRecord.setExecuteCourtName("临海市人民法院");
        executeRecord.setCreateUserId(userDTO.getUserId().toString());
        executeRecord.setCreateUserName(userDTO.getRealName());
        executeRecord.setExecuteResult(Constant.STRING_0);
        executeRecord.setExecuteContent(JSON.toJSON(paramMap).toString());
        executeRecord.setCreateTime(LocalDateTime.now());
        //保存执行情况记录
        try {
            saveNonLitigationExecuteAutoRecord(executeRecord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjectUtil.isEmpty(record)) {
            executeRecord.setId(BaseUtil.createUid());
            executeRecord.setCreateTime(LocalDateTime.now());
            executeRecord.setExecuteFailReason(errorMsg);
            caseNonLitigationExecuteRecordMapper.insertSelective(executeRecord);
        } else {
            executeRecord.setId(record.getId());
            executeRecord.setExecuteFailReason(errorMsg);
            caseNonLitigationExecuteRecordMapper.updateByPrimaryKeySelective(executeRecord);
        }
        resultMap.put("errorMsg", errorMsg);
        return resultMap;
    }

    @Override
    public CaseNonLitigationExecuteRecord getCaseNonLitigationExecuteRecordByCaseId(String caseId) {
        Example example = new Example(CaseNonLitigationExecuteRecord.class);
        example.createCriteria().andEqualTo("caseId", caseId);
        List<CaseNonLitigationExecuteRecord> caseNonLitigationExecuteRecords = caseNonLitigationExecuteRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(caseNonLitigationExecuteRecords)) {
            return caseNonLitigationExecuteRecords.get(0);
        }
        return null;
    }

    @Override
    public Map<String, Object> saveNonLitigationExecuteAutoRecord(CaseNonLitigationExecuteRecord record) {
        StageDocCommonOperateSaveDto saveDto = new StageDocCommonOperateSaveDto();
        String caseId = record.getCaseId();
        HashMap<String, Object> dataMap = new HashMap<>();
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseId);
        String partyName = casePartiesInfo.stream().map(e -> e.getPartyName()).collect(Collectors.joining("、"));

        dataMap.put("ZXQKJL_DSR", partyName);
        //获取宽表信息
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        if (ObjectUtils.isEmpty(caseMainDetailInfo)) {
            throw new BusinessException("未匹配到案件详情-caseId：" + caseId);
        }
        LocalDateTime executeFinishDate = record.getCreateTime();
        String tmp = executeFinishDate.format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        //执行完成日期
        dataMap.put("ZXQKJL_ZXWCRQ", tmp);

        //执行情况描述
        String executeConditionDesc = caseMainDetailInfo.getExecuteConditionDesc();
        //执行方式
        dataMap.put("ZXQKJL_ZXFS", "强制执行");
        //相关证据材料法院	NONLITIGATION_COURT
        //获取返回附件
        CaseAttachmentInfoQueryDto attachmentInfoQueryDto = new CaseAttachmentInfoQueryDto();
        attachmentInfoQueryDto.setCaseId(caseId);
        List<CaseAttachmentInfoVo> caseAttachmentList = caseAppendixRecordService.getCaseAttachmentList(attachmentInfoQueryDto);
        List<String> urlList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(caseAttachmentList)) {
            for (CaseAttachmentInfoVo caseAttachmentInfoVo : caseAttachmentList) {
                String appendixTypeId = caseAttachmentInfoVo.getAppendixTypeId();
                if (appendixTypeId.contains("NONLITIGATION_COURT")) {
                    urlList.add(caseAttachmentInfoVo.getAppendixUrl());
                }

            }
        }
        dataMap.put("ZXQKJL_ZJCL", urlList);
        //获取办案人员
        List<CaseHandlePersonRecordVo> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        String mainHandlerName = "";
        String assistHandlerName = "";
        String mainHandlerCert = "";
        String assistHandlerCert = "";
        for (CaseHandlePersonRecordVo handler : caseHandlePersonRecordList) {
            String handlePersonType = handler.getHandlePersonType();
            if (Constant.STRING_1.equals(handlePersonType)) {
                //主办
                mainHandlerName = handler.getHandlePersonName();
                mainHandlerCert = handler.getLawEnforcementCert();
            } else {
                //协办
                assistHandlerName = handler.getHandlePersonName();
                assistHandlerCert = handler.getLawEnforcementCert();
            }
            if (!ObjectUtils.isEmpty(mainHandlerName) && !ObjectUtils.isEmpty(assistHandlerName)) {
                break;
            }
        }
        dataMap.put("ZXQKJL_ZBRYXM", mainHandlerName);
        dataMap.put("ZXQKJL_ZBRYZFZH", mainHandlerCert);

        dataMap.put("ZXQKJL_XBRYXM", assistHandlerName);
        dataMap.put("ZXQKJL_XBRYZFZH", assistHandlerCert);
        //处罚决定书文号 CFJDSWH
        String kindCode = Constant.STRING_KIND_CODE_CFJDS;
        CaseDocumentRecordDto documentRecord = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, kindCode);
        if (ObjectUtils.isEmpty(documentRecord)) {
            throw new BusinessException("未匹配到-caseId:" + caseId + ",kindCode:" + kindCode);
        }
        String documentCatalogCode;
        List<ConfigBusiParamDocumentInfo> configList = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId, null, kindCode);
        if (!ObjectUtils.isEmpty(configList)) {
            documentCatalogCode = configList.get(Constant.INTEGER_0).getDocumentCatalogCode();
        } else {
            throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + kindCode);
        }

        String documentNumber = caseMainDetailInfo.getPunishDocumentNumber();
        dataMap.put("ZXQKJL_BZ", documentNumber);
        saveDto.setCaseId(caseId);
        saveDto.setDocumentCatalogCode(documentCatalogCode);
        saveDto.setDataMap(dataMap);
        saveDto.setIsUpdateRelationTable(YesOrNoEnum.NO.getCode());
        String partyIds = casePartiesInfo.stream().map(e -> e.getPartyId()).collect(Collectors.joining(","));
        saveDto.setPartyId(partyIds);
        return stageDocCommonOperateService.saveDocInfo(saveDto);
    }

    @Override
    public List<CaseNonLitigationExecuteRecordVo> getCaseNonLitigationExecuteVoList(CaseNonLitigationExecutePageRequest pageRequest) {
        checkOrgCode(pageRequest);
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getLength());
        List<CaseNonLitigationExecuteRecordVo> voList = caseNonLitigationExecuteRecordMapper.selectCaseNonLitigationExecuteRecordVoList(pageRequest);
        for (CaseNonLitigationExecuteRecordVo vo : voList) {
            vo.setExecuteStatusName(CaseNonLitigationExecuteStatusEnum.getValueByCode(vo.getExecuteStatus()));
            //5.如果是公司主体，返回公司信息
            if (vo.getPartyType().equals(Constant.STRING_2)) {
                CasePartiesLegalInfo legalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(vo.getPartyId());
                vo.setLegalInfo(legalInfo);
            }
        }

        return voList;
    }

    @Override
    public CaseNonLitigationExecuteDetailVo getNonLitigationExecuteDetail(NonLitigationExecuteConditionRecordQueryDto queryDto) {
        //查询附件
        List<AppendixDto> appendixList = new ArrayList<>();
        CaseAttachmentInfoQueryDto attachmentInfoQueryDto = new CaseAttachmentInfoQueryDto();
        queryDto.setCaseId(queryDto.getCaseId());
        List<CaseAttachmentInfoVo> caseAttachmentList = caseAppendixRecordService.getCaseAttachmentList(attachmentInfoQueryDto);
        if (ObjectUtil.isNotEmpty(caseAttachmentList)) {
            for (CaseAttachmentInfoVo caseAttachmentInfoVo : caseAttachmentList) {
                String appendixTypeId = caseAttachmentInfoVo.getAppendixTypeId();
                if ("EVIDENCE".equals(appendixTypeId)
                        || "BUSINESS_LICENCE_CERT".equals(appendixTypeId)
                        || "USER_CARD".equals(appendixTypeId)) {
                    AppendixDto appendixDto = new AppendixDto();
                    CaseDocumentRecordUploadDto uploadDto = new CaseDocumentRecordUploadDto();
                    appendixDto.setAppendixName(caseAttachmentInfoVo.getAppendixName());
                    appendixDto.setAppendixTypeId(caseAttachmentInfoVo.getAppendixType());
                    appendixDto.setAppendixUrl(caseAttachmentInfoVo.getAppendixUrl());
                    appendixList.add(appendixDto);
                }
            }
        }
        return null;
    }

    @Override
    public CaseNonLitigationExecuteRecordDetailVo getNonLitigationExecuteConditionRecord(NonLitigationExecuteConditionRecordQueryDto queryDto) {
        CaseNonLitigationExecuteRecordDetailVo detailVo = new CaseNonLitigationExecuteRecordDetailVo();
        CaseDocumentRecordVo caseDocumentRecordInfo = caseDocumentRecordService.getCaseDocumentRecordInfo(queryDto.getDocumentId());
//        if (ObjectUtil.isEmpty(caseDocumentRecordInfo)){
//            throw new BusinessException("没有执行记录存在");
//        }
        detailVo.setDocumentUrl(caseDocumentRecordInfo.getDocumentUrl());
        CaseNonLitigationExecuteRecord executeRecord = getCaseNonLitigationExecuteRecordByCaseId(queryDto.getCaseId());
        if (ObjectUtil.isEmpty(caseDocumentRecordInfo)) {
            throw new BusinessException("没有提交非诉执行");
        }
        detailVo.setExecuteCourtCode(executeRecord.getExecuteCourtCode());
        detailVo.setExecuteCourtName(executeRecord.getExecuteCourtName());
        detailVo.setCreateTime(executeRecord.getCreateTime());
        detailVo.setCourtCaseTime(executeRecord.getCreateTime());
        //获取非诉执行情况
        CaseMainDetailInfo caseMainInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(queryDto.getCaseId());
        detailVo.setCaseId(caseMainInfo.getCaseId());
        detailVo.setAdrApprovalTypeId(caseMainInfo.getAdrApprovalTypeId());
        detailVo.setAdrApprovalTypeName(caseMainInfo.getAdrApprovalTypeName());
        detailVo.setCaseInvolveId(caseMainInfo.getCaseInvolveId());
        detailVo.setCaseInvolveName(caseMainInfo.getCaseInvolveName());
        detailVo.setJurisdictionBasisId(caseMainInfo.getJurisdictionBasisId());
        detailVo.setJurisdictionBasisName(caseMainInfo.getJurisdictionBasisName());

        // 获取关联文书信息
        List<NonLitigationPartiesMaterialInfo> materialInfos = new ArrayList<>();
        NonLitigationPartiesMaterialInfo materialInfo = new NonLitigationPartiesMaterialInfo();
        CaseDocumentRecordDto record = caseDocumentRecordService.getCaseDocumentRecordByKindCode(queryDto.getCaseId(), DocumentKindEnum.DOC_KIND_QZZXSQS.getCode());
        materialInfo.setDocumentName(record.getDocumentKindName());
        materialInfo.setDocumentUrl(record.getDocumentUrlAfterSeal());
        materialInfos.add(materialInfo);
        detailVo.setRelateDocumentList(materialInfos);
        //获取返回附件
        List<AppendixDto> appendixList = new ArrayList<>();
        CaseAttachmentInfoQueryDto attachmentInfoQueryDto = new CaseAttachmentInfoQueryDto();
        queryDto.setCaseId(queryDto.getCaseId());
        List<CaseAttachmentInfoVo> caseAttachmentList = caseAppendixRecordService.getCaseAttachmentList(attachmentInfoQueryDto);
        if (ObjectUtil.isNotEmpty(caseAttachmentList)) {
            for (CaseAttachmentInfoVo caseAttachmentInfoVo : caseAttachmentList) {
                String appendixTypeId = caseAttachmentInfoVo.getAppendixTypeId();
                if (appendixTypeId.contains("NONLITIGATION_COURT")) {
                    AppendixDto appendixInfo = new AppendixDto();
                    appendixInfo.setAppendixName(caseAttachmentInfoVo.getAppendixName());
                    appendixInfo.setAppendixTypeId(caseAttachmentInfoVo.getAppendixType());
                    appendixInfo.setAppendixUrl(caseAttachmentInfoVo.getAppendixUrl());
                    appendixInfo.setAppendixTypeId(caseAttachmentInfoVo.getAppendixTypeId());
                    appendixInfo.setAppendixType(caseAttachmentInfoVo.getAppendixType());
                    appendixList.add(appendixInfo);
                }

            }
        }
        detailVo.setAppendixList(appendixList);
        return detailVo;
    }

    @Override
    public CaseNonLitigationExecuteRecord getCaseNonLitigationExecuteRecordByNonLitigationCaseId(String nonLitigationCaseId) {
        Example example = new Example(CaseNonLitigationExecuteRecord.class);
        example.createCriteria().andEqualTo("nonLitigationCaseId", nonLitigationCaseId);
        List<CaseNonLitigationExecuteRecord> caseNonLitigationExecuteRecords = caseNonLitigationExecuteRecordMapper.selectByExample(example);
        if (ObjectUtil.isNotEmpty(caseNonLitigationExecuteRecords)) {
            return caseNonLitigationExecuteRecords.get(0);
        }
        return null;
    }

    @Override
    public Result<String> saveDecisionResult(NonLitigationExecuteResultSaveDto saveDto) {
        String nonLitigationExecuteId = saveDto.getNonLitigationCaseId();
        CaseNonLitigationExecuteRecord executeRecord = this.getCaseNonLitigationExecuteRecordByNonLitigationCaseId(nonLitigationExecuteId);
        if (ObjectUtils.isEmpty(executeRecord)) {
            return Result.error("非诉执行记录不存在");
        }
        logger.info("非诉执行保存裁决结果返回参数，{}", JSON.toJSON(saveDto).toString());
        CaseNonLitigationExecuteRecord updateExecuteRecord = new CaseNonLitigationExecuteRecord();
        updateExecuteRecord.setId(executeRecord.getId());
        if (Constant.STRING_1.equals(saveDto.getDecisionResult())) {
            updateExecuteRecord.setExecuteStatus(Constant.STRING_2);
        }
        updateExecuteRecord.setNonLitigationCaseId(nonLitigationExecuteId);
        updateExecuteRecord.setDecisionDocumentUrlId(saveDto.getDecisionDocumentUrl());
        updateExecuteRecord.setDecisionDocumentNumber(saveDto.getDecisionDocumentNumber());
        updateExecuteRecord.setDecisionDate(saveDto.getDecisionDate());
        updateExecuteRecord.setUpdateTime(LocalDateTime.now());
        int count = caseNonLitigationExecuteRecordMapper.updateByPrimaryKeySelective(updateExecuteRecord);
        if (count > 0) {
            return Result.success("数据接收成功");
        }
        return Result.error("数据接收失败");
    }

    /**
     * orgCode处理
     *
     * @param request
     * @author shishengyao
     * @date 2022/05/28
     */
    private void checkOrgCode(CaseNonLitigationExecutePageRequest request) {
        request.setOrg(0);
        if (org.apache.commons.lang3.StringUtils.isEmpty(request.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = request.getOrgCode().split(",");

        for (String s : str) {
            if (s.indexOf("_") > 0) {
                orgCodeList.add(s);
            } else {
                deptCodeList.add(s);
            }
        }
        if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
            request.setOrg(1);
        } else if (orgCodeList.size() > 0) {
            request.setOrg(2);
        } else if (deptCodeList.size() > 0) {
            request.setOrg(3);
        }

        request.setOrgCodeList(orgCodeList);
        request.setDeptCodeList(deptCodeList);
    }

    /**
     * 描述：组装申请材料信息
     *
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/07
     */
    List<Map<String, Object>> assembleApplicationMaterial(CaseNonLitigationExecuteRequestDto requestDto, String token) {
        List<Map<String, String>> paramList = new ArrayList<>();
        List<CaseDocumentRecordDto> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentRecordList(requestDto.getCaseId(), "");
        //1.强制执行申请书（必传）
        //2.行政处罚决定书（必传） 送达回证
        //3.行政决定履行催告书（必传）
        //4.诉讼参与人主体资格材料（包含委托手续）（必传）
        //5.证据材料
        //6.处罚告知书 告知书送达回证
        List<CaseDocumentRecordUploadDto> uploadDtoList = new ArrayList<>();
        int count = 1;
        for (CaseDocumentRecordDto caseDocumentRecord : caseDocumentRecordList) {
            Map<String, String> fileMap = new HashMap<>();
            if (ObjectUtil.isNotEmpty(caseDocumentRecord.getDocumentUrlAfterSign())) {
                fileMap.put("fileUrl", caseDocumentRecord.getDocumentUrlAfterSign());
            } else if (ObjectUtil.isNotEmpty(caseDocumentRecord.getDocumentUrlAfterSeal())) {
                fileMap.put("fileUrl", caseDocumentRecord.getDocumentUrlAfterSeal());
            } else {
                fileMap.put("fileUrl", caseDocumentRecord.getDocumentUrl());
            }
            fileMap.put("filebh", String.valueOf(count));
            fileMap.put("fileId", caseDocumentRecord.getId());
            CaseDocumentRecordUploadDto uploadDto = new CaseDocumentRecordUploadDto();
            BeanUtils.copyProperties(caseDocumentRecord, uploadDto);
            String fileName = StringUtil.isEmpty(caseDocumentRecord.getDocumentNumber())
                    ? caseDocumentRecord.getDocumentKindName() : caseDocumentRecord.getDocumentNumber();
            uploadDto.setFileName(fileName + ".pdf");
            uploadDto.setDocumentCatalogCode(caseDocumentRecord.getDocumentCatalogCode());
            uploadDto.setFileUrl(caseDocumentRecord.getDocumentUrl());
            uploadDto.setFileNum(String.valueOf(count));
            if (Constant.STRING_KIND_CODE_CFJDS.equals(caseDocumentRecord.getDocumentKindCode())
                    || "QZZXSQS".equals(caseDocumentRecord.getDocumentKindCode())
                    || "XZJDLXCGS".equals(caseDocumentRecord.getDocumentKindCode())
                    || "CFGZSTZL".equals(caseDocumentRecord.getDocumentKindCode())
                    || "CFGZS".equals(caseDocumentRecord.getDocumentKindCode())) {

                paramList.add(fileMap);
                uploadDto.setMaterialTypeCode(NonLitigationApplicationMaterialEnum.getCodeByRelCode(caseDocumentRecord.getDocumentKindCode()));
                uploadDto.setMaterialTypeName(NonLitigationApplicationMaterialEnum.getDesByRelCode(caseDocumentRecord.getDocumentKindCode()));
                uploadDto.setMaterialDesc(NonLitigationApplicationMaterialEnum.getDesByRelCode(caseDocumentRecord.getDocumentKindCode()));
                uploadDtoList.add(uploadDto);
                count++;
            } else if (Constant.STRING_KIND_CODE_SDHZ.equals(caseDocumentRecord.getDocumentKindCode())) {
                if (caseDocumentRecord.getDocumentCatalogCode().contains("CFGZSPB")) {
                    uploadDto.setMaterialTypeCode(NonLitigationApplicationMaterialEnum.CFGZS.getCode());
                    uploadDto.setMaterialTypeName(NonLitigationApplicationMaterialEnum.CFGZS.getDes());
                }
                if (caseDocumentRecord.getDocumentCatalogCode().contains(NonLitigationApplicationMaterialEnum.XZCFJDS.getCode())) {
                    uploadDto.setMaterialTypeCode(NonLitigationApplicationMaterialEnum.XZCFJDS.getCode());
                    uploadDto.setMaterialTypeName(NonLitigationApplicationMaterialEnum.XZCFJDS.getDes());
                }
                if (caseDocumentRecord.getDocumentCatalogCode().contains(NonLitigationApplicationMaterialEnum.XZJDLXCGS.getCode())) {
                    uploadDto.setMaterialTypeCode(NonLitigationApplicationMaterialEnum.XZJDLXCGS.getCode());
                    uploadDto.setMaterialTypeName(NonLitigationApplicationMaterialEnum.XZJDLXCGS.getDes());
                }
                paramList.add(fileMap);
                uploadDtoList.add(uploadDto);
                count++;
            }

        }
        //4.诉讼参与人主体资格材料（包含委托手续）（必传） 5.证据材料
        CaseAttachmentInfoQueryDto queryDto = new CaseAttachmentInfoQueryDto();
        queryDto.setCaseId(requestDto.getCaseId());
        List<CaseAttachmentInfoVo> caseAttachmentList = caseAppendixRecordService.getCaseAttachmentList(queryDto);
        if (ObjectUtil.isNotEmpty(caseAttachmentList)) {
            for (CaseAttachmentInfoVo caseAttachmentInfoVo : caseAttachmentList) {
                String appendixTypeId = caseAttachmentInfoVo.getAppendixTypeId();
                if ("EVIDENCE".equals(appendixTypeId)
                        || "BUSINESS_LICENCE_CERT".equals(appendixTypeId)
                        || "USER_CARD".equals(appendixTypeId)) {
                    Map<String, String> fileMap = new HashMap<>();
                    fileMap.put("fileUrl", caseAttachmentInfoVo.getAppendixUrl());
                    fileMap.put("filebh", String.valueOf(count));
                    fileMap.put("fileId", caseAttachmentInfoVo.getId());
                    paramList.add(fileMap);
                    CaseDocumentRecordUploadDto uploadDto = new CaseDocumentRecordUploadDto();
                    uploadDto.setDocumentCatalogCode("");
                    String url = caseAttachmentInfoVo.getAppendixUrl();
                    if (StringUtils.isNotEmpty(url)) {
                        String str1 = url.substring(0, url.lastIndexOf("."));
                        String str2 = url.substring(str1.length(), url.length());
                        if (caseAttachmentInfoVo.getAppendixName().contains(".")) {
                            uploadDto.setFileName(caseAttachmentInfoVo.getAppendixName());
                        } else {
                            uploadDto.setFileName(caseAttachmentInfoVo.getAppendixName() + str2);
                        }

                    }
                    uploadDto.setFileUrl(caseAttachmentInfoVo.getAppendixUrl());
                    uploadDto.setMaterialTypeCode(NonLitigationApplicationMaterialEnum.getCodeByRelCode(appendixTypeId));
                    uploadDto.setMaterialTypeName(NonLitigationApplicationMaterialEnum.getDesByRelCode(appendixTypeId));
                    uploadDto.setMaterialDesc(NonLitigationApplicationMaterialEnum.getDesByRelCode(appendixTypeId));
                    uploadDto.setFileNum(String.valueOf(count));
                    uploadDtoList.add(uploadDto);
                    count++;
                }

            }
        }
        //将文件上传到法院，获取编号
        JSONArray uploadFileList = uploadFileList(paramList, token);
        //外网诉服中心编号wwstbh ; 实体编号 nwstbh ;  唯一编号filebh
        List<Map<String, Object>> materialList = new ArrayList<>();
        Map<String, List<CaseDocumentRecordUploadDto>> collect = uploadDtoList.stream().collect(Collectors.groupingBy(CaseDocumentRecordUploadDto::getMaterialTypeCode));
        for (Map.Entry<String, List<CaseDocumentRecordUploadDto>> entry : collect.entrySet()) {
            List<Map<String, Object>> fileInfoList = new ArrayList<>();
            Map<String, Object> materialMap = new HashMap<>();
            List<CaseDocumentRecordUploadDto> values = entry.getValue();
            int pageNum = 0;
            for (CaseDocumentRecordUploadDto uploadDto : values) {
                for (Object material : uploadFileList) {
                    JSONObject parse = JSONObject.parseObject(material.toString());
                    if (uploadDto.getFileNum().equals(parse.getString("filebh"))) {
                        Map<String, Object> fileInfoMap = new HashMap<>();
                        //材料分类
                        fileInfoMap.put("qsclfl", uploadDto.getMaterialTypeCode() == null ? "5" : uploadDto.getMaterialTypeCode());
                        //材料分类名称
                        fileInfoMap.put("clfl_mc", uploadDto.getMaterialTypeName() == null ? "证据材料" : uploadDto.getMaterialTypeName());
                        //材料说明
                        fileInfoMap.put("clsm", uploadDto.getMaterialTypeName());
                        //  fileInfoMap.put("nwstbh", parse.getString("nwstbh"));
                        fileInfoMap.put("nwstbh", parse.getString("wwstbh"));
                        //文件名
                        fileInfoMap.put("file_name", uploadDto.getFileName());
                        //材料顺序号
                        fileInfoMap.put("pagenum", pageNum + 1);
                        fileInfoList.add(fileInfoMap);
                        //材料总份数
                        pageNum++;
                        continue;
                    }
                }
            }
            materialMap.put("fileInfo", fileInfoList);
            materialMap.put("pagesize", values.size());
            materialList.add(materialMap);
        }
        return materialList;
    }

    /**
     * 描述：组装申请材料信息
     *
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/07
     */
    private void assembleParamInfo(Map<String, Object> paramMap, String caseId, UserDTO userDTO) {
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        CaseReasonMainRecordVo caseReasonRecord = caseReasonMainRecordService.getCaseReasonRecordByCaseId(caseId);
        List<CaseHandlePersonRecord> personList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseId);
        CaseDocumentRecord xzcfjds = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_CFJDS);
        if (ObjectUtil.isEmpty(xzcfjds)) {
            throw new BusinessException("行政处罚决定书未生成");
        } else if (ObjectUtil.isEmpty(xzcfjds.getSentTime())) {
            throw new BusinessException("行政处罚决定书未送达!");
        }
        CaseDocumentRecord cgsInfo = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, "XZJDLXCGS");
        if (ObjectUtil.isEmpty(cgsInfo)) {
            throw new BusinessException("行政履行催告书未生成!");
        } else if (ObjectUtil.isEmpty(cgsInfo.getSentTime())) {
            throw new BusinessException("行政履行催告书未送达!");
        }
        CaseHandlePersonRecord caseHandlePersonRecord = new CaseHandlePersonRecord();
        personList.forEach(e -> {
            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                BeanUtils.copyProperties(e, caseHandlePersonRecord);
            }
        });

        Map<String, Object> ajxxMap = new HashMap<>();
        //1、ajxx（案件基本信息）
        //案件类型代码默认94,非诉行政行为申请执行审查案件（AJLXDM=94）
        ajxxMap.put("ajlx", "94");
        ajxxMap.put("ajlx_mc", "非诉行政行为申请执行审查案件");

        ajxxMap.put("ay", caseReasonRecord.getCaseReasonCode());
        ajxxMap.put("ay_mc", caseReasonRecord.getCaseReasonName());
        //被申请人人申辩情况 1-当事人在法定期限内对上述行政文书未申请行政复议或提起行政诉讼，也未履行行政文书 2-其他
        ajxxMap.put("bsqrsbqk", "1");
        ajxxMap.put("bsqrsbqkqt", "");
        //todo 案件涉及情况 宽表取值
        //案件涉及
        ajxxMap.put("xzfsajsj", caseMainDetailInfo.getAdrApprovalTypeName());
        //管辖依据
        ajxxMap.put("xzfsgxyj", caseMainDetailInfo.getJurisdictionBasisName());
        //非诉审查类型
        ajxxMap.put("xzfssclx", caseMainDetailInfo.getJurisdictionBasisName());
        ajxxMap.put("ssqladsr_zjlx", "");
        ajxxMap.put("xtbh", ACCESS_XTBH);
        ajxxMap.put("xzxwzl", XZXWZL_CODE);
        //催告书编号
        ajxxMap.put("cgsbh", cgsInfo.getDocumentNumber());
        ajxxMap.put("cgssdsj", cgsInfo.getSentTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //法院 fixme 法院名称待定
        ajxxMap.put("fybm1", COURT_CODE);
        ajxxMap.put("fymc", "临海市人民法院");
        //被申请人人履行情况 1- 当事人在规定期限内仍未履行该决定 2- 当事人在规定期限内部分履行该决定 3- 其他
        ajxxMap.put("lxsk", "1");
        ajxxMap.put("lxqkmx", "");
        //人民法庭(非必填)
        ajxxMap.put("rmft", "");
        ajxxMap.put("rmft_mc", "");
        // fixme 提交申请人用机构  立案人类型暂定执法局
        //ajxxMap.put("sqladsr_name", userDTO.getRealName());
        ajxxMap.put("sqladsr_name", "蒋雨蒙");
        SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseHandlePersonRecord.getHandleOrgCode(), caseHandlePersonRecord.getHandleDeptCode());
        ajxxMap.put("sqladsr_zjh", sysDepartParam.getUnicode());
        ajxxMap.put("sqladsr_zjlx", NonLitigationCertTypeEnum.TYSHXYDM.getCode());
        //提交立案申请人类型 1.自然人 2.组织机构
        ajxxMap.put("sqlarlx", "2");
        ajxxMap.put("sqlarlx_mc", sysDepartParam.getOrgStandardName());
        //请求事项
        List<String> sqnrList = new ArrayList<>();
        sqnrList.add(caseMainDetailInfo.getPunishContent());
        ajxxMap.put("sqnr", sqnrList);
        //处罚金额
        ajxxMap.put("ssbdje", StringUtils.isEmpty(caseMainDetailInfo.getDraftPunishMoney()) ? 0 : caseMainDetailInfo.getDraftPunishMoney());
        //获取处罚决定相关信息（处罚决定书目录编码：CFJDS0F62A）
        ajxxMap.put("xzay", "");
        //行政处罚决定书送达时间
        ajxxMap.put("xzwssdsj", xzcfjds.getSentTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        ajxxMap.put("wsbh", xzcfjds.getDocumentNumber());
        //行政处罚决定书作出时间
        ajxxMap.put("xzwszcsj", xzcfjds.getDocumentCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        paramMap.put("ajjbxx", ajxxMap);

        //2、dsrxx(当事人信息)
        List<Map<String, Object>> dsrxxList = assembleCasePartiesInfoList(caseId, sysDepartParam);
        paramMap.put("dsrxx", dsrxxList);

        //3、dlrxx(代理人信息)
        // todo 代理人信息没有
        List<Map<String, Object>> dlrxxList = new ArrayList<>();
        Map<String, Object> dlrxxMap = new HashMap<>();
        int dlrxxCount = 4001;
        for (CaseHandlePersonRecord handlePersonRecord : personList) {
            // 序号 4001
            if (Constant.STRING_1.equals(handlePersonRecord.getHandlePersonType())) {
                dlrxxMap.put("dlrbh", dlrxxCount);
                dlrxxMap.put("mc", handlePersonRecord.getHandlePersonName());
                //类别，代码字典12 15_000005-6 负责人
                dlrxxMap.put("lb", "15_000005-6");
                //固定15_000004-1，无需传值
                dlrxxMap.put("lx", "15_000004-1");
                //代理人类型，代码字典7
                dlrxxMap.put("dlrlx", "");
                //辩护人类型，代码字典14
                dlrxxMap.put("bhrlx", "");
                //与当事人关系，代码字典13
                dlrxxMap.put("ydsrgx", "");
                //性别，代码如下：
                dlrxxMap.put("xb", NonLitigationSexEnum.getCodeByDes(""));
                //国别或地区 15_GB0006-44中国
                dlrxxMap.put("gbhdq", "15_GB0006-44");
                //目前没有，默认为汉族
                dlrxxMap.put("mz", "15_GB0002-01");
                //证件号
                dlrxxMap.put("sfzhm", "420921199006054879");
                //是否法律援助律师,1:是，2：否
                dlrxxMap.put("sfflyz", "2");
                //律师执业资格证号
                dlrxxMap.put("lszyzgzh", "");
                //工作单位或律所名称
                dlrxxMap.put("gzdw", "");
                //律所组织机构代码
                dlrxxMap.put("lszzjgdm", "");
                //职务
                dlrxxMap.put("zw", "代理人");
                //手机号码
                dlrxxMap.put("sjhm", StringUtils.isEmpty(handlePersonRecord.getHandleDeptTel()) ? sysDepartParam.getPhone() : handlePersonRecord.getHandleDeptTel());
                //办公电话
                dlrxxMap.put("bgdh", StringUtils.isEmpty(handlePersonRecord.getHandleDeptTel()) ? sysDepartParam.getPhone() : handlePersonRecord.getHandleDeptTel());
                //地址
                dlrxxMap.put("dz", sysDepartParam.getAddress());
                //同意电子送达，1、是，2、否
                dlrxxMap.put("dzsd", "2");
                dlrxxCount++;
                dlrxxList.add(dlrxxMap);
            }

        }
        paramMap.put("dlrxx", dlrxxList);

    }

    /**
     * 描述：组装当事人信息（申请人和被申请人）
     *
     * @param caseId
     * @param sysDepartParam sys离开参数
     * @return {@link List<Map<String, Object>> }
     * @author shishengyao
     * @date 2022/04/11
     */
    public List<Map<String, Object>> assembleCasePartiesInfoList(String caseId, SysDepartParam sysDepartParam) {
        List<Map<String, Object>> dsrxxList = new ArrayList<>();
        //申请人
        String count = "0001";
        Map<String, Object> sqrDsrxxMap = new HashMap<>();
        sqrDsrxxMap.put("xh", count);
        sqrDsrxxMap.put("mc", sysDepartParam.getOrgStandardName().replace("\r", ""));
        //当事人诉讼地位： 15_060053-1 申请人，15_060053-2被申请人
        sqrDsrxxMap.put("ssdw", "15_060053-1");
        //国别  默认中国
        sqrDsrxxMap.put("gbhdq", "15_GB0006-44");
        sqrDsrxxMap.put("lx", NonLitigationPartyTypeEnum.LEGAL.getCode());
        sqrDsrxxMap.put("dz", sysDepartParam.getAddress());
        //代码类型 1-组织机构代码，2-统一社会信用代码
        sqrDsrxxMap.put("dmlx", "1");
        sqrDsrxxMap.put("shtyxydm", "");
        sqrDsrxxMap.put("zzjgdm", sysDepartParam.getUnicode());
        // todo 法定代表人信息目前没有，暂写
        sqrDsrxxMap.put("fddbr", "罗文");
        //代表人证件种类，字典6
        sqrDsrxxMap.put("dbrzjzl", "");
        sqrDsrxxMap.put("dbrzjhm", "");
        sqrDsrxxMap.put("fddbrzw", "局长");
        sqrDsrxxMap.put("dwxz", "15_000118-33");
        sqrDsrxxMap.put("dzsd", "2");
        sqrDsrxxMap.put("sddz", sysDepartParam.getAddress());
        dsrxxList.add(sqrDsrxxMap);
        //当事人
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseId);
        for (CasePartiesRecordVo casePartiesRecordVo : casePartiesInfo) {
            Map<String, Object> dsrxxMap = new HashMap<>();
            dsrxxMap.put("xh", count);
            dsrxxMap.put("mc", casePartiesRecordVo.getPartyName());
            //当事人诉讼地位： 15_060053-1 申请人，15_060053-2被申请人
            dsrxxMap.put("ssdw", "15_060053-2");
            //国别  默认中国
            dsrxxMap.put("gbhdq", "15_GB0006-44");
            String partyType = NonLitigationPartyTypeEnum.getCodeByRelCode(casePartiesRecordVo.getPartyType());
            CasePartiesDetailInfoVo casePartiesDetailInfoVo = casePartiesRecordService.getCasePartiesDetailInfo(caseId);
            dsrxxMap.put("lx", partyType);
            if (NonLitigationPartyTypeEnum.PERSON.getCode().equals(partyType)) {
                CasePartiesPersonInfoVo personInfoVo = casePartiesDetailInfoVo.getCasePartiesPersonInfo();
                dsrxxMap.put("xb", NonLitigationSexEnum.getCodeByDes(personInfoVo.getSex()));
                dsrxxMap.put("csrq", personInfoVo.getBirth());
                dsrxxMap.put("sfzhm", personInfoVo.getCertNo());
                dsrxxMap.put("sjhm", personInfoVo.getMobile());
                dsrxxMap.put("dz", personInfoVo.getAddress());
                dsrxxMap.put("szdw", personInfoVo.getUnitName());
                dsrxxMap.put("dmlx", "");
                //目前没有，默认为汉族
                dsrxxMap.put("mz", "15_GB0002-01");
                //单位性质默认其他
                dsrxxMap.put("dwxz", "15_000118-33");
                dsrxxMap.put("sddz", personInfoVo.getAddress());
            } else {
                CasePartiesLegalInfoVo legalInfo = casePartiesDetailInfoVo.getCasePartiesLegalInfo();
                dsrxxMap.put("dz", legalInfo.getAddress());
                dsrxxMap.put("zzjgdm", legalInfo.getUniscid());
                //代码类型 1-组织机构代码，2-统一社会信用代码
                dsrxxMap.put("dmlx", "2");
                dsrxxMap.put("shtyxydm", legalInfo.getUniscid());
                dsrxxMap.put("fddbr", legalInfo.getLegalName());
                dsrxxMap.put("dbrzjzl", "");
                dsrxxMap.put("dbrzjhm", "");
                dsrxxMap.put("fddbrzw", legalInfo.getJob());
                //单位性质默认其他
                dsrxxMap.put("dwxz", "15_000118-33");
                dsrxxMap.put("sddz", legalInfo.getAddress());
            }
            //送达地址
            DocumentSentAddressInfoRequest request = new DocumentSentAddressInfoRequest();
            request.setCaseId(caseId);
            //TODO:当事人id按需传入
            CaseDocumentSendinfoConfirmVo sendInfo = caseDocumentSendinfoConfirmService.getCaseDocumentSendInfoConfirmInfo(request);
            if (ObjectUtil.isNotEmpty(sendInfo)) {
                dsrxxMap.put("sddz", sendInfo.getPickMobile());
                //同意电子送达，1、是，2、否
                dsrxxMap.put("dzsd", "1");
            } else {

                dsrxxMap.put("dzsd", "2");
            }
            // 没有代理人 ，不填
            dsrxxMap.put("ssdlrbh", "");
            dsrxxMap.put("cxzh", "");
            dsrxxMap.put("cxmm", "");
            //非必填信息
            dsrxxMap.put("qtzjzl", "");
            dsrxxMap.put("qtzjhm", "");
            dsrxxMap.put("zy", "");
            dsrxxMap.put("whcd", "");
            dsrxxMap.put("dzyx", "");
            dsrxxMap.put("hjszd", "");
            dsrxxMap.put("dzss", "");
            dsrxxMap.put("wx", "");

            dsrxxList.add(dsrxxMap);
            //代表四位数
            DecimalFormat decimalFormat = new DecimalFormat("0000");
            count = decimalFormat.format(Integer.parseInt(count) + 1);
        }
        return dsrxxList;
    }

    /**
     * 描述：传入文件地址获取实体编号
     *
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/07
     */
    public String uploadFile(String token, String fileUrl) {
        token = "Bearer " + token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("fileUrl", fileUrl);
        paramMap.put("fydm", COURT_CODE);
        try {
            String result = HttpUtils.doHttpPostWithToken(url + uploadFile, token, paramMap);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (ObjectUtil.isNotEmpty(jsonObject.get("code"))) {
                    if (Constant.STRING_200.equals(jsonObject.get("code").toString())) {
                        JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                        token = data.getString("token");
                        logger.info("Non-litigation execute upload file success，result:{}", result);
                    } else {
                        logger.info("Non-litigation Execute upload file fail，result:{}", result);
                    }
                } else {
                    throw new BusinessException("Non-litigation Execute upload file fail，result:{}" + jsonObject.get("code"));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }


    /**
     * 描述：批量上传文件获取实体编号
     *
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/07
     */
    public JSONArray uploadFileList(List<Map<String, String>> fileList, String token) {
        token = "Bearer " + token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("fydm", COURT_CODE);
        paramMap.put("fileList", fileList);
        try {
            String result = NonLitigationUtil.doIRSHttpPostWithToken(url + uploadFileList, token, paramMap);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (ObjectUtil.isNotEmpty(jsonObject.getString("code"))) {
                    if (Constant.STRING_200.equals(jsonObject.getString("code"))) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        logger.info("Non-litigation Execute upload file successfully，result:" + data);
                        return data;
                    } else {
                        logger.info("Non-litigation Execute upload file fail，result:" + result);
                        throw new BusinessException(jsonObject.getString("msg"));
                    }
                } else {
                    throw new BusinessException(jsonObject.getString("message"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return null;
    }

    /**
     * 描述：获取调用授权
     *
     * @return {@link String }
     * @author shishengyao
     * @date 2022/04/07
     */

    public String getBearerToken(String ipAddress) {
        String token = "";
        //默认服务器ip
        String addr = "10.142.2.152";
//        try {
//            InetAddress localHostAddr = InetAddress.getLocalHost();
//            addr = ObjectUtil.isEmpty(localHostAddr) ? addr : localHostAddr.toString();
//        } catch (UnknownHostException e) {
//            logger.info("" + e.getMessage());
//        }
        Map<String, Object> paramMap = new HashMap<>();
        //接入系统编号
        paramMap.put("access_xtbh", ACCESS_XTBH);
        //访问接入系统服务的终端ip
        paramMap.put("ip", addr);
        //访问接入系统的登陆人姓名
        paramMap.put("name", "");
        //访问接入系统的登陆人身份证号
        paramMap.put("idNumber", "");
        //访问接入系统用途
        paramMap.put("use", "行政非诉智审网上立案");
        //接入系统名称
        paramMap.put("csxtmc", "统一处罚办案系统");
        //接入系统调用接口时间
        paramMap.put("time", LocalDateTime.now());

        try {
            logger.info("Non-litigation Execute get token，paramMap:{}" , JSONObject.toJSONString(paramMap));
            // 服务用户名密码 lhxzhzhx / 728605d6
            String username = "lhxzhzhx";
            String password = "728605d6";
            String basicToken = "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes());
            String result = NonLitigationUtil.doIRSHttpPostWithToken(url + getToken, basicToken, paramMap);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if (Constant.STRING_200.equals(jsonObject.get("code").toString())) {
                    JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                    token = data.getString("token");
                    logger.info("Non-litigation Execute get token success，result:{}" , result);
                } else {
                    logger.info("Non-litigation Execute get token Fail，result:{}" , result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("Non-litigation Execute get token Fail,result:" + e.getMessage());
        }
        return token;
    }
}
